﻿using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Devonline.Identity;

/// <summary>
/// 访问规则, 字符串类型的默认实现
/// </summary>
[Table("access_rule"), Display(Name = "访问规则")]
public class AccessRule : AccessRule<string>, IEntitySet, IEntitySetWithCreate, IEntitySetWithCreateAndUpdate
{
    /// <summary>
    /// 资源
    /// </summary>
    public virtual Resource Resource { get; set; }
}

/// <summary>
/// 访问规则
/// 简易模式访问规则, 满足规则即允许访问
/// </summary>
[Table("access_rule"), Display(Name = "访问规则")]
public class AccessRule<TKey> : EntitySetWithCreateAndUpdate<TKey>, IEntitySet<TKey>, IEntitySetWithCreate<TKey>, IEntitySetWithCreateAndUpdate<TKey> where TKey : IConvertible
{
    /// <summary>
    /// 资源编号
    /// </summary>
    [Column("resource_id"), DisplayName("资源编号"), MaxLength(36), Excel]
    public virtual TKey ResourceId { get; set; }
    /// <summary>
    /// 授权对象
    /// 资源授权使用的主体
    /// </summary>
    [Column("identity_id"), DisplayName("授权对象编号"), MaxLength(36), Excel]
    public virtual TKey IdentityId { get; set; }
    /// <summary>
    /// 授权对象类型, IdentityType 枚举值
    /// </summary>
    [Column("identity_type", TypeName = "VARCHAR(16)"), DisplayName("授权对象类型"), DefaultValue(IdentityType.Role), Excel]
    public virtual IdentityType IdentityType { get; set; }

    /// <summary>
    /// 规则编号
    /// 针对资源访问的统一规则制定的总体约束, 形如: R35, #35
    /// </summary>
    [Column("code", TypeName = "VARCHAR(16)"), DisplayName("规则编号"), MaxLength(16), Excel]
    public virtual string Code { get; set; }
    /// <summary>
    /// 是否允许 AllowType 枚举值
    /// </summary>
    [Column("is_allow", TypeName = "VARCHAR(16)"), DisplayName("是否允许"), DefaultValue(AllowType.Allow), Excel]
    public virtual AllowType IsAllow { get; set; }
    /// <summary>
    /// 优先级, 当前规则的优先级
    /// </summary>
    [Column("priority"), DisplayName("优先级"), Excel]
    public virtual int Priority { get; set; }
    /// <summary>
    /// 过期时间限制, 访问授权的有效期
    /// </summary>
    [Column("expire_time"), DisplayName("过期时间"), Excel]
    public virtual DateTime? ExpireTime { get; set; }
    /// <summary>
    /// 访问次数, 默认 0
    /// </summary>
    [Column("access_count"), DisplayName("访问次数"), Excel]
    public virtual int AccessCount { get; set; }
    /// <summary>
    /// 访问次数限制, 即最大可访问次数, 0 表示不限制
    /// </summary>
    [Column("limit_access_count"), DisplayName("访问次数限制"), Excel]
    public virtual int LimitAccessCount { get; set; }
    /// <summary>
    /// 条件
    /// 符合条件则执行 AllowType 策略
    /// 规则构成为简单的 {变量 条件 值} 形式, 一行一个, 暂不支持复杂表达式
    /// 如: {userName eq 'admin'}
    /// 支持的条件表达式详见枚举类型: OperatorType
    /// </summary>
    [Column("condition"), DisplayName("条件"), MaxLength(1024), Excel]
    public virtual string Condition { get; set; }
}